package com.db.httpserver;

import java.io.IOException;
import java.net.BindException;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Server implements Runnable {
	private ServerSocket providerSocket;
	private Socket socket;
	private int port;
	private int workers = Parameter.getWorkers();
	private ExecutorService executor = Executors.newFixedThreadPool(workers);

	public Server(int port) {
		this.port = port;
	}

	public void run() {

		try {
			providerSocket = new ServerSocket(port, 10);
			System.out.println("Waiting for connection on" + " IP: "
					+ InetAddress.getLocalHost().getHostAddress() + " Port : "
					+ port);

			while (true) {
				socket = providerSocket.accept();
				executor.execute(new WorkerThread(socket));
			}

		} catch (BindException bindExc) {
			System.out.println(bindExc.getMessage());
		} catch (IOException ioException) {
			ioException.printStackTrace();
		} finally {
			try {
				providerSocket.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}
